package helper

import (
	"gin_study_blog/common"
	"gin_study_blog/models"
	"gorm.io/gorm"
)

type Option struct {
	models.PageInfo
	Debug bool
	Likes []string
}

// CommonList 封装列表查询 泛型
func CommonList[T any](model T, option Option) (list []T, count int64, err error) {

	DB := common.DB
	if option.Debug {
		DB = common.DB.Session(&gorm.Session{Logger: common.MysqlLog})
	}

	if option.Sort == "" {
		option.Sort = "created_at DESC" // 时间往前排倒叙
	}

	page := (option.Page - 1) * option.Limit
	if page < 0 {
		page = 0
	}

	// 这里的 query 受上面的查询影响,组装 where
	query := DB.Model(model).Where(model)

	err = query.
		Count(&count).Offset(page).Limit(option.Limit).
		Order(option.Sort).Find(&list).Error

	return list, count, err
}
